package net.starwifi.duobao.interceptor;


import net.starwifi.duobao.entity.Member;
import net.starwifi.duobao.oauth.Principal;
import net.starwifi.duobao.service.GglUserService;
import net.starwifi.duobao.service.MemberService;
import net.starwifi.duobao.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * 话费购参数透传
 * Created by Administrator on 2015/7/30.
 */
public class HFGHelperInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    MemberService memberService;
    @Autowired
    GglUserService gglUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
        if (principal != null) {
            return true;
        } else {
            String paramText=request.getParameter("a");
            String paramMobile=request.getParameter("mobile");
            String cp=request.getParameter("cp");
            if(paramText==null&&paramMobile==null){//透传参数为空
                return true;
            }
            try {
                String pMobile=null;
                if(paramText!=null){
                    pMobile=DesHelper.decrypt(paramText);
                }
                if(cp!=null){
                   try {
                       if(paramMobile!=null&&cp.equals("200")){
                           pMobile= AesHelper.aesDecrypt(paramMobile);
                       } else if(paramMobile!=null&&cp.equals("201")){
                           pMobile= EncodeUtils.decode(EncodeUtils.seed,paramMobile);
                       }else {
                           pMobile=DesHelper.decrypt(paramMobile);
                       }
                   }catch (Exception e){
                       e.printStackTrace();
                   }
                }
                if(pMobile==null){
                    return true;
                }
                if(pMobile.length()<11){
                    return true;
                }
                Member member=memberService.findByMobile(pMobile);
                if (member == null) {
                    member=new Member();
                    member.setUsername("m" + pMobile);
                    String salt= net.starwifi.duobao.utils.StringUtils.getUUID();
                    member.setSalt(salt);
                    member.setMobile(pMobile);
                    member.setIsEnabled(true);
                    member.setIsLocked(false);
                    member.setLoginFailureCount(0);
                    member.setLockedDate(null);
                    member.setBalance(BigDecimal.ZERO);
                    member.setCurrencyBalance(BigDecimal.ZERO);
                    member.setVirtualCurrency(BigDecimal.ZERO);
                    try {
                        if(request.getSession().getAttribute("cp")!=null){
                            member.setCpId((String)request.getSession().getAttribute("cp"));
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (!member.getIsEnabled()) {
                    return true;
                }
                if(member.getVirtualCurrency()==null){
                    member.setVirtualCurrency(BigDecimal.ZERO);
                }
                member.setLoginIp(IpUtils.getIpAddr(request));
                member.setLoginDate(new Date());
                member.setLoginFailureCount(0);
                if(member.getId()==null){
                    memberService.save(member);

                }else{
                    memberService.update(member);
                }
                //获取登录时间
                gglUserService.saveLog(member);

                Map<String, Object> attributes = new HashMap<String, Object>();
                Enumeration<?> keys = session.getAttributeNames();
                while (keys.hasMoreElements()) {
                    String key = (String) keys.nextElement();
                    attributes.put(key, session.getAttribute(key));
                }
                session.invalidate();
                session = request.getSession();
                for (Map.Entry<String, Object> entry : attributes.entrySet()) {
                    session.setAttribute(entry.getKey(), entry.getValue());
                }
                String userAgent=request.getHeader("User-Agent");
                String cookiePass=DigestUtils.md5Hex(userAgent + member.getPassword());
                session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), pMobile));
                session.setAttribute("pMobile",pMobile);
                WebUtils.addCookie(request, response, Member.COOKIE_USERNAME_NAME, member.getUsername());
                WebUtils.addCookie(request, response, Member.COOKIE_PASS_NAME, cookiePass);
                return true;
            }catch (Exception e){
                e.printStackTrace();
                return true;
            }
        }
    }


}
